//
//  RoomPkViewController.m
//  TRTC-API-Example-OC
//
//  Created by bluedang on 2021/4/22.
//

/*
 跨房PK功能
 TRTC 跨房PK
 
 本文件展示如何集成跨房PK
 
 1、连接其他房间 API: [self.trtcCloud connectOtherRoom:jsonString];
 
 参考文档：https://cloud.tencent.com/document/product/647/32258
 */
/*
 Cross-room Competition
 The TRTC app supports cross-room competition.

 This document shows how to integrate the cross-room competition feature.

 1. Connect to another room: [self.trtcCloud connectOtherRoom:jsonString]

 Documentation: https://cloud.tencent.com/document/product/647/32258
 */

#import "RoomPkViewController.h"

@interface RoomPkViewController () <TRTCCloudDelegate>

@property (weak, nonatomic) IBOutlet UILabel *otherRoomIdLabel;
@property (weak, nonatomic) IBOutlet UILabel *otherUserIdLabel;

@property (weak, nonatomic) IBOutlet UIView *localView;
@property (weak, nonatomic) IBOutlet UIView *remoteView;
@property (weak, nonatomic) IBOutlet UITextField *otherRoomIdTextField;
@property (weak, nonatomic) IBOutlet UITextField *otherUserIdTextField;

//@property (weak, nonatomic) IBOutlet UIButton *startButton;
@property (weak, nonatomic) IBOutlet UIButton *connectOtherRoomButton;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;

@property (nonatomic, assign) NSString *otherRoomId;

@property (nonatomic, assign) NSString *otherUserId;

@property (weak, nonatomic) IBOutlet UIButton *stopPushBtn;

@property (weak, nonatomic) IBOutlet UIButton *stopCdnPublishBtn;


@property (weak, nonatomic) IBOutlet UIButton *stopMixBtn;


@property (nonatomic, assign) BOOL isPking;

@property (strong, nonatomic) TRTCCloud *trtcCloud;

@property (strong, nonatomic) TRTCTranscodingConfig *transcodingConfig;

@property (nonatomic, assign) BOOL mixStoped;

@end

@implementation RoomPkViewController

- (instancetype)initWithRoomId:(NSString *)roomId userId:(NSString *)userId {
    if (self = [super init]) {
        self.localRoomId = roomId;
        self.localUserId = userId;
    }
    return self;
}

- (TRTCCloud*)trtcCloud {
    if (!_trtcCloud) {
        _trtcCloud = [TRTCCloud sharedInstance];
        [_trtcCloud createSubCloud];
    }
    return _trtcCloud;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.trtcCloud setDelegate:self];
    [self setupDefaultUIConfig];
    [self setupNaviBarStatus];
    
    [self setupTRTCCloud];
}



- (void)setupNaviBarStatus {
//    self.navigationItem.title = Localize(@"TRTC-API-Example.Home.Title");
    [self.navigationController setNavigationBarHidden:false animated:false];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    self.navigationController.navigationBar.translucent = YES;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
}

- (void)setupDefaultUIConfig {
    
    self.title = [Localize(@"TRTC-API-Example.RoomPk.title") stringByAppendingString:self.localRoomId];
    _otherRoomIdLabel.text = Localize(@"TRTC-API-Example.RoomPk.pkRoomId");
    _otherUserIdLabel.text = Localize(@"TRTC-API-Example.RoomPk.pkUserId");

    [_connectOtherRoomButton setTitle:Localize(@"TRTC-API-Example.RoomPk.startPK")
                  forState:UIControlStateNormal];
    [_connectOtherRoomButton setTitle:Localize(@"TRTC-API-Example.RoomPk.stopPK")
                  forState:UIControlStateSelected];
    _otherRoomIdLabel.adjustsFontSizeToFitWidth = true;
    _otherUserIdLabel.adjustsFontSizeToFitWidth = true;
    _connectOtherRoomButton.titleLabel.adjustsFontSizeToFitWidth = true;
    _otherRoomIdLabel.adjustsFontSizeToFitWidth = true;
    _otherUserIdLabel.adjustsFontSizeToFitWidth = true;
//    [self refreshPkButton];
    [self addKeyboardObserver];
    
    [self.connectOtherRoomButton setBackgroundColor:[UIColor themeGreenColor]];
    
    [self.stopPushBtn setBackgroundColor:[UIColor themeGreenColor]];
    [self.stopPushBtn setTitle:@"停止推流" forState:UIControlStateSelected];
    self.stopPushBtn.selected = YES;
    
    [self.stopCdnPublishBtn setBackgroundColor:[UIColor themeGreenColor]];
    [self.stopCdnPublishBtn setTitle:@"停止CDN推送" forState:UIControlStateSelected];
    [self.stopCdnPublishBtn.titleLabel setAdjustsFontSizeToFitWidth:YES];
    self.stopCdnPublishBtn.selected = YES;
    
    [self.stopMixBtn setBackgroundColor:[UIColor themeGreenColor]];
    [self.stopMixBtn setTitle:@"停止混流" forState:UIControlStateSelected];
    self.stopMixBtn.selected = YES;
}


- (void)setupTRTCCloud {
    [self.trtcCloud startLocalPreview:YES view:_localView];

    TRTCParams *params = [TRTCParams new];
    params.sdkAppId = SDKAppID;
    params.roomId = (UInt32)[self.localRoomId integerValue];
    params.userId = self.localUserId;
    params.role = TRTCRoleAnchor;
    params.userSig = [GenerateTestUserSig genTestUserSig:params.userId];
    
    [self.trtcCloud enterRoom:params appScene:TRTCAppSceneLIVE];
    
    TRTCVideoEncParam *videoEncParam = [TRTCVideoEncParam new];
    
    videoEncParam.videoResolution = TRTCVideoResolution_1280_720;
    videoEncParam.videoBitrate = 1500;
    videoEncParam.videoFps = 15;
    
    [self.trtcCloud setVideoEncoderParam:videoEncParam];
    [self.trtcCloud startLocalAudio:TRTCAudioQualityDefault];
}

- (void)destroyTRTCCloud {
    [TRTCCloud destroySharedIntance];
    _trtcCloud = nil;
}

- (void)dealloc {
    [self.trtcCloud exitRoom];
    [self destroyTRTCCloud];
    [self removeKeyboardObserver];
}

- (BOOL)checkPkRoomAndUserIdIsValid {
    if (_otherRoomIdTextField.text && ![_otherRoomIdTextField.text isEqualToString:@""]) {
        if (_otherUserIdTextField.text && ![_otherUserIdTextField.text isEqualToString:@""]) {
            return true;
        }
    }
    return false;
}

//- (void)refreshPkButton {
//    if ([_startButton isSelected]) {
//        [_connectOtherRoomButton setEnabled:true];
//        [_connectOtherRoomButton setBackgroundColor:[UIColor themeGreenColor]];
//    } else {
//        [_connectOtherRoomButton setEnabled:false];
//        [_connectOtherRoomButton setBackgroundColor:[UIColor themeGrayColor]];
//    }
//}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:true];
}

#pragma mark - IBActions


- (IBAction)onStartPkClick:(UIButton*)sender {
    sender.selected = !sender.selected;
    if ([sender isSelected] && [self checkPkRoomAndUserIdIsValid]) {
        NSMutableDictionary * jsonDict = [[NSMutableDictionary alloc] init];
        [jsonDict setObject:@([_otherRoomIdTextField.text intValue]) forKey:@"roomId"];
        [jsonDict setObject:_otherUserIdTextField.text forKey:@"userId"];
        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:nil];
        NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        [self.trtcCloud connectOtherRoom:jsonString];
//        [sender setTitle:@"结束PK" forState:UIControlStateNormal];
        
    } else {
        sender.selected = false;
        [self.trtcCloud disconnectOtherRoom];
//        [sender setTitle:@"开始PK" forState:UIControlStateNormal];
    }
}

- (void)updateTranscodingConfig {
    
    if (self.mixStoped) return;
    
    NSMutableArray *mixUsers = [[NSMutableArray alloc] init];

    TRTCMixUser* local = [TRTCMixUser new];
    local.userId = self.localUserId;
    local.zOrder = 1;
    local.rect   = CGRectMake(0, 0, self.transcodingConfig.videoWidth * 0.5, self.transcodingConfig.videoHeight / 2);
    local.roomID = nil;
    [mixUsers addObject:local];
    
    // 当前处于PK状态
    if (self.otherUserId) {
        TRTCMixUser* remote = [TRTCMixUser new];
        remote.userId = self.otherUserId;
        remote.zOrder = 0;
        remote.rect   = CGRectMake(self.transcodingConfig.videoWidth * 0.5, 0, self.transcodingConfig.videoWidth * 0.5, self.transcodingConfig.videoHeight/2);
        remote.roomID = self.otherRoomId;
        [mixUsers addObject:remote];
    }
   
    self.transcodingConfig.mixUsers = mixUsers;
    
    [self.trtcCloud setMixTranscodingConfig:self.transcodingConfig];
}


- (IBAction)stopMix:(UIButton *)sender {
    // 停止混流
    sender.selected = !sender.selected;
    if (sender.selected) {
        self.mixStoped = NO;
        [self updateTranscodingConfig];
    }
    else {
        self.mixStoped = YES;
        [self.trtcCloud setMixTranscodingConfig:nil];
    }
    
}


- (IBAction)stopLocalStream:(UIButton *)sender {
    // 断流
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.trtcCloud startLocalPreview:YES view:_localView];
        [self.trtcCloud startLocalAudio:TRTCAudioQualityDefault];
    }
    else {
        [self.trtcCloud stopLocalPreview];
        [self.trtcCloud stopLocalAudio];
    }
    
}

- (IBAction)stopPublishCdn:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self updateTranscodingConfig];
        [self.trtcCloud startPublishing:@"live" type:TRTCVideoStreamTypeBig];
    }
    else {
        [self.trtcCloud stopPublishing];
    }
}



- (TRTCTranscodingConfig *)transcodingConfig {
    if (!_transcodingConfig) {
        _transcodingConfig = [[TRTCTranscodingConfig alloc] init];
        _transcodingConfig.mode = TRTCTranscodingConfigMode_Manual;
        _transcodingConfig.videoWidth      = 750;
        _transcodingConfig.videoHeight     = 1280;
        _transcodingConfig.videoBitrate    = 1500;
        _transcodingConfig.videoFramerate  = 20;
        _transcodingConfig.videoGOP        = 2;
        _transcodingConfig.audioSampleRate = 48000;
        _transcodingConfig.audioBitrate    = 64;
        _transcodingConfig.audioChannels   = 2;
        _transcodingConfig.appId   = CDNAPPID;
        _transcodingConfig.bizId   = CDNBIZID;
        _transcodingConfig.backgroundColor = 0x000000;
        _transcodingConfig.backgroundImage = nil;
    }
    return _transcodingConfig;
}



#pragma mark - Notification
- (void)addKeyboardObserver {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeKeyboardObserver {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (BOOL)keyboardWillShow:(NSNotification *)noti {
    CGFloat animationDuration = [[[noti userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect keyboardBounds = [[[noti userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:animationDuration animations:^{
        self.bottomConstraint.constant = keyboardBounds.size.height;
    }];
    return YES;
}

- (BOOL)keyboardWillHide:(NSNotification *)noti {
     CGFloat animationDuration = [[[noti userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
     [UIView animateWithDuration:animationDuration animations:^{
         self.bottomConstraint.constant = 20;
     }];
     return YES;
}


#pragma mark - TRTCCloud Delegate

- (void)onEnterRoom:(NSInteger)result {
    if (result > 0) {
        [self.trtcCloud startPublishing:@"live" type:TRTCVideoStreamTypeBig];
    }
}

- (void)onUserVideoAvailable:(NSString *)userId available:(BOOL)available {
    if (![userId isEqualToString:_otherUserIdTextField.text]) {
        return;
    }
    if (available) {
        [_trtcCloud startRemoteView:userId streamType:TRTCVideoStreamTypeBig view:_remoteView];
        self.otherUserId = userId;
        [self updateTranscodingConfig];
    } else {
//        self.otherUserId = nil;
//        [self updateTranscodingConfig];
        [_trtcCloud stopRemoteView:userId streamType:TRTCVideoStreamTypeBig];
    }
}

- (void)onConnectOtherRoom:(NSString *)userId errCode:(TXLiteAVError)errCode errMsg:(NSString *)errMsg {
    if (errCode != ERR_NULL) {
        [self showAlertViewController:Localize(@"TRTC-API-Example.RoomPk.connectRoomError") message:errMsg handler:nil];
        _connectOtherRoomButton.selected = NO;
    }
    else {
        self.otherRoomId = self.otherRoomIdTextField.text;
        self.otherUserId = self.otherUserIdTextField.text;
        self.isPking = YES;
        _connectOtherRoomButton.selected = YES;
    }
}

- (void)onDisconnectOtherRoom:(TXLiteAVError)errCode errMsg:(NSString *)errMsg {
    if (errCode != ERR_NULL) {
    }
    else {
        self.isPking = NO;
    }
}

- (void)onSetMixTranscodingConfig:(int)err errMsg:(NSString *)errMsg {
    NSLog(@"onSetMixTranscodingConfig err: %d, errMsg: %@", err, errMsg);
}

- (void)onStartPublishing:(int)err errMsg:(NSString *)errMsg {
    NSLog(@"onStartPublishing err: %d, errMsg: %@", err, errMsg);
}

- (void)onStartPublishCDNStream:(int)err errMsg:(NSString *)errMsg {
    NSLog(@"onStartPublishCDNStream err: %d, errMsg: %@", err, errMsg);
}

@end
